import React, {useEffect, useState} from 'react';
import {createPortal} from 'react-dom';
import {X, CheckCircle, AlertCircle, Info, AlertTriangle} from 'lucide-react';
import {useToastStore} from '@/stores/toast';
import {cn} from '@/lib/utils';

// Toast图标映射
const toastIcons = {
    success: CheckCircle,
    error: AlertCircle,
    info: Info,
    warning: AlertTriangle,
};

// Toast样式映射
const toastStyles = {
    success: 'bg-success-50 border-success-200 text-success-800',
    error: 'bg-danger-50 border-danger-200 text-danger-800',
    info: 'bg-primary-50 border-primary-200 text-primary-800',
    warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
};

// Toast消息类型（本地定义）
interface ToastMessageLocal {
    id: string;
    message: string;
    type: 'success' | 'error' | 'info' | 'warning';
    duration?: number;
}

// 单个Toast组件属性
interface ToastItemProps {
    // 消息数据
    message: ToastMessageLocal;
    // 移除回调
    onRemove: (id: string) => void;
}

// 单个Toast项目组件
const ToastItem: React.FC<ToastItemProps> = ({message, onRemove}) => {
    const [isVisible, setIsVisible] = useState(false);
    const [isExiting, setIsExiting] = useState(false);

    const IconComponent = toastIcons[message.type as keyof typeof toastIcons];

    // 进入动画
    useEffect(() => {
        const timer = setTimeout(() => setIsVisible(true), 10);
        return () => clearTimeout(timer);
    }, []);

    // 处理移除
    const handleRemove = () => {
        setIsExiting(true);
        setTimeout(() => {
            onRemove(message.id);
        }, 200);
    };

    // 自动移除
    useEffect(() => {
        if (message.duration && message.duration > 0) {
            const timer = setTimeout(() => {
                handleRemove();
            }, message.duration);

            return () => clearTimeout(timer);
        }
        return undefined;
    }, [message.duration]);

    return (
        <div
            className={cn(
                // 基础样式
                'flex items-start gap-3 p-4 rounded-lg border shadow-lg',
                'transform transition-all duration-200 ease-out',
                'max-w-sm w-full pointer-events-auto',
                // 类型样式
                toastStyles[message.type as keyof typeof toastStyles],
                // 动画状态
                isVisible && !isExiting && 'translate-x-0 opacity-100',
                !isVisible && 'translate-x-full opacity-0',
                isExiting && 'translate-x-full opacity-0 scale-95'
            )}
            role="alert"
            aria-live="polite"
        >
            {/* 图标 */}
            <IconComponent
                size={20}
                className="flex-shrink-0 mt-0.5"
            />

            {/* 消息内容 */}
            <div className="flex-1 min-w-0">
                <p className="text-sm font-medium whitespace-pre-wrap break-words">
                    {message.message}
                </p>
            </div>

            {/* 关闭按钮 */}
            <button
                type="button"
                onClick={handleRemove}
                className="flex-shrink-0 p-0.5 rounded-md hover:bg-black hover:bg-opacity-10 transition-colors"
                aria-label="关闭通知"
            >
                <X size={16}/>
            </button>
        </div>
    );
};

// Toast容器组件
export const ToastContainer: React.FC = () => {
    const {messages, removeToast} = useToastStore();

    // 如果没有消息，不渲染任何内容
    if (messages.length === 0) return null;

    return createPortal(
        <div
            className='fixed z-50 flex flex-col gap-2 pointer-events-none top-20 right-4'
            aria-live="polite"
            aria-label="通知消息"
        >
            {messages.map((message) => (
                <ToastItem
                    key={message.id}
                    message={message}
                    onRemove={removeToast}
                />
            ))}
        </div>,
        document.body
    );
};

// Toast Hook（简化使用）
export const useToastNotification = () => {
    const {showSuccess, showError, showInfo, showWarning} = useToastStore();

    return {
        success: (message: string) =>
            showSuccess(message),

        error: (message: string) =>
            showError(message),

        info: (message: string) =>
            showInfo(message),

        warning: (message: string) =>
            showWarning(message),
    };
};
